<?php

namespace app\admin\controller;

use app\model\GoodsAgency;
use app\model\GoodsAudit;
use think\exception\ValidateException;
use app\model\Goods;
use app\model\Category;
use app\model\GoodsDescription;
use app\model\GoodsImage;
use app\model\GoodsSku;
use app\model\GoodsSkuValue;
use app\model\GoodsShareCharges;
use app\model\Store;
use app\model\Config;
use app\model\MemberAuthGroup;
use app\model\GoodsMemberDiscount;
use app\model\Operatingcity;
use app\model\Area;

class GoodsController extends Base
{

	function index()
	{
		$weid = weid();
		$page = input('post.page', 1, 'intval');
		$keyword = input('post.keyword', '', 'serach_in');
		$cat_id = input('post.cat_id', '', 'serach_in');
		$ptype = input('post.ptype', '', 'serach_in');
		$is_recommand = input('post.is_recommand', '', 'serach_in');
		$status = input('post.status', '', 'serach_in');
        $audit_status = input('post.audit_status','','serach_in');
        $ocid         = input('post.ocid',0);
        if($ocid >0){
            $where['ocid'] = $ocid;
        }else{
            $where['ocid'] = 0;
        }
        $where['weid'] = $weid;
        $data['ocid'] = 0;
		if(!empty($this->ocid)){
		    $model  = new GoodsAudit();
            $where['ocid'] =  $data['ocid']  =  $this->ocid;
        }else{
            $model  = new Goods();
        }
		$query = $model->where($where);
		if(!$ocid){
//            $query->whereNull('city_name');
        }

		if (!empty($ptype)) {
			$query->where('ptype', $ptype);
		} else {
			$query->where('ptype', '>', 0);
		}
		if (!empty($this->sid)) {
            $StoreInfo =  Store::where(['id'=>$this->sid])->find();
//			$query->where('sid', $this->sid);
            $query->whereIn('cat_id',$StoreInfo['cate_ids'])->where('city_name', $StoreInfo['city_name']);
		}
		if (!empty($this->ocid)) {
			$Operatingcitydata = Operatingcity::find($this->ocid);
			if ($Operatingcitydata) {
				$Operatingcitydata = $Operatingcitydata->toArray();
				if ($Operatingcitydata['areatype'] == 2) {
					$query->where('district_name', $Operatingcitydata['district_name']);
				} elseif ($Operatingcitydata['areatype'] == 1) {
					$query->where('city_name', $Operatingcitydata['city_name']);
				}
			}
		}

		if (!empty($keyword)) {
			$query->where('name', 'like', '%' . $keyword . '%');
		}

		if (!empty($cat_id)) {
			$query->where('cat_id',  $cat_id);
		}

		if (!empty($is_recommand) || $is_recommand === "0") {
			$query->where('is_recommand', $is_recommand);
		}

		if($audit_status){
            $query->where('audit_status', $audit_status);
        }

		if (!empty($status) || $status === "0") {
			$query->where(['status' => $status]);
		}

		$res = $query->order('id desc')
			->paginate(getpage())
			->toArray();

		foreach ($res['data'] as &$vo) {
			$vo['image'] = toimg($vo['image']);
            if(!empty($this->ocid)){
               $vo['price'] =  Goods::where(['id'=>$vo['goods_id']])->value('price');
            }
			if ($vo['sid'] == 0) {
//				$vo['name'] = $vo['name'];
			} else {
				$StoreTitle = Store::getTitle($vo['sid']);
				if (empty($StoreTitle)) {
					$vo['name'] = '[商户已被删除]' . $vo['name'];
				} else {
					$vo['name'] = '[' . $StoreTitle . ']' . $vo['name'];
				}
			}
            $vo['daili_name'] = '';
			if($vo['ocid']){
			    $userInfo = Operatingcity::where(['id'=>$vo['ocid']])->with(['user'])->find();
			    $vo['daili_name'] = $userInfo['user']['username'];
            }
			$vo['cat_id'] = Category::getTitle($vo['cat_id']);
			$vo['create_time'] = time_format($vo['create_time']);
			$vo['update_time'] = time_format($vo['update_time']);
            $vo['fwaddress'] = $vo['province_name'].$vo['city_name'];
            if($vo['is_points_goods'] == 1){
                $vo['price'] = $vo['pay_points'];
            }
		}
		$data['data'] = $res;
		if ($page == 1) {
			$data['field_data']['cidarray'] = _generateSelectTree(Category::getpcarray($ptype));
		}
		return $this->json($data);
	}

	function listUpdate()
	{
//		$data = only('id,is_recommand,is_additional,status,sort');
		$data = input('post.');
		if (!$data['id']) throw new ValidateException('参数错误');
        if(!empty($this->ocid)){
            $model  = new GoodsAudit();
        }else{
            $model  = new Goods();
        }
       $model->update($data);
		return $this->json(['msg' => '操作成功']);
	}

	public function update()
	{
		$id = request()->post('id');
		$data = input('post.');
		$data['update_time'] = time();
		$data['image'] = $data['images'][0]['url'];
        if(!empty($this->ocid)){
            $goods_moel  = new GoodsAudit();
            if($id){
                $data['audit_status'] = 1;
            }
        }else{
            $goods_moel  = new Goods();
        }
		if ($data['cat_id']) {
			$cat = Category::find($data['cat_id']);
			if (!empty($cat)) {
				$cat = $cat->toArray();
			}
			$data['ptype'] = $cat['ptype'];
			$data['deliverymode'] = $cat['deliverymode'];
		}
		if (!empty($data['videourl'])) {
			$data['videotype'] = 1;
		} elseif (!empty($data['videoid'])) {
			$data['videotype'] = 2;
		} else {
			$data['videotype'] = 0;
		}

		if (empty($id)) {
			$data['weid'] = weid();
			$data['create_time'] = time();
			if (!empty($this->sid)) {
				$data['sid'] = $this->sid;

				$storemod = Store::find($this->sid);
				if ($storemod) {
					$data['province_name'] = $storemod->province_name;
					$data['city_name'] = $storemod->city_name;
					$data['district_name'] = $storemod->district_name;
				}
			}
			if (!empty($this->ocid)) {
				$data['ocid'] = $this->ocid;
                $ocmod = Operatingcity::find($this->ocid);
                if ($ocmod) {
                    $data['province_name'] = $ocmod->province_name;
                    $data['city_name'] = $ocmod->city_name;
                    $data['district_name'] = $ocmod->district_name;
                }
			}


			if (empty($data['tel'])) {
				$data['tel'] = '';
			}
			try {
                    if(!empty($data['agency_json'])){
                        $agency_arr = json_decode($data['agency_json'],true);
                         foreach ($agency_arr as $k=>$v){
                             $data['ocid']  = $v['ocid'];
                             $data['price'] = $v['price'];
                             $ocmod = Operatingcity::find($data['ocid']);
                             if ($ocmod) {
                                 $data['province_name'] = $ocmod->province_name;
                                 $data['city_name']     = $ocmod->city_name;
                                 $data['district_name'] = $ocmod->district_name;
                             }
                             $res = Goods::create($data);
                             if ($res->id && empty($data['sort'])) {
                                 $goods_moel->update(['sort' => $res->id, 'id' => $res->id]);
                             }
                             $data['id'] = $res->id;
                             $this->_synupdata($data);
                             if($res->id){
                                 unset($data['id']);
                                 $towArray = $data;
                                 $towArray['goods_id'] = $res->id;
                                 $towArray['audit_status'] = 2;
                                 $towArray['create_time']  = time();
                                 $towArray['audit_time']   = time();
                                 $towArray['update_time']  = time();
                                 GoodsAudit::create($towArray);
                             }
                         }
                         unset($data['agency_json']);
                        $data['province_name'] = null;
                        $data['city_name']     = null;
                        $data['district_name'] = null;
                        $data['ocid']          = 0;
                        $res =  Goods::create($data);
                        $data['id'] = $res->id;
                        $this->_synupdata($data);
                    }else{
//                        throw new ValidateException('参数错误');
                        $res = $goods_moel->create($data);
                        if ($res->id && empty($data['sort'])) {
                            $goods_moel->update(['sort' => $res->id, 'id' => $res->id]);
                        }
                        $data['id'] = $res->id;
                        $this->_synupdata($data);
                    }

			} catch (\Exception $e) {
				throw new ValidateException($e->getMessage());
			}
            if($res->id){
                return $this->json(['msg' => '添加成功']);
            }else{
                return $this->json(['msg' => '失败']);
            }

		} else {

			try {
                if(!empty($this->ocid)){
                    $goods_moel->update($data);
                    $data['id'] = GoodsAudit::where(['id'=>$data['id']])->value('goods_id');
                }else{
                    $goods_id = $data['id'];
                    $goodsAuditinfo = GoodsAudit::where(['goods_id'=>$goods_id])->find();
                    if($goodsAuditinfo){
                        unset($data['id']);
                        GoodsAudit::where(['goods_id'=>$goods_id])->update($data);
                    }
                    $data['id'] = $goods_id;
                    $goods_moel->update($data);
                }

				$this->_synupdata($data);
			} catch (\Exception $e) {
				throw new ValidateException($e->getMessage());
			}

			return $this->json(['msg' => '修改成功']);
		}
	}

	function _synupdata($data)
	{
		//详情
		if (empty(GoodsDescription::where('goods_id', $data['id'])->find())) {
			GoodsDescription::create([
				'goods_id' => (int) $data['id'],
				'description' => $data['description']
			]);
		} else {
			GoodsDescription::where('goods_id', $data['id'])->update(['description' => $data['description']]);
		}

		//sku

		GoodsSku::where('goods_id', $data['id'])->delete();
		if (isset($data['attribute'])) {
			foreach ($data['attribute'] as $attr) {
				GoodsSku::create([
					'goods_id' => (int) $data['id'],
					'name' => $attr['name'],
					'ptype' => 'radio',
					'item' =>  implode(',', $attr['item'])
				]);
			}
		}

		GoodsSkuValue::where('goods_id', $data['id'])->delete();
		if (isset($data['sku'])) {
			foreach ($data['sku'] as $skuarr) {
				GoodsSkuValue::create([
					'goods_id' => (int) $data['id'],
					'sku' => $skuarr['sku'],
					'image' => $skuarr['image'],
					'quantity' => $skuarr['quantity'],
					'price' => $skuarr['price']
				]);
			}
		}

		GoodsShareCharges::where('goods_id', $data['id'])->delete();
		if (!empty($data['is_share_charges']) && !empty($data['sharecharges'])) {
			foreach ($data['sharecharges'] as $scvo) {
				if ($scvo['price'] > 0) {
					GoodsShareCharges::create([
						'goods_id' => (int) $data['id'],
						'level' => $scvo['level'],
						'price' => (float) $scvo['price'],
						'charges_method' => (int) $data['charges_method']
					]);
				}
			}
		}

		GoodsMemberDiscount::where('goods_id', $data['id'])->delete();
		if (!empty($data['is_member_discount']) && !empty($data['MemberGroup'])) {
			foreach ($data['MemberGroup'] as $mgvo) {
				if ($mgvo['price'] > 0) {
					GoodsMemberDiscount::create([
						'goods_id' => (int) $data['id'],
						'mgid' => (int) $mgvo['id'],
						'price' => (float) $mgvo['price']
					]);
				}
			}
		}
		//图片
		GoodsImage::where('goods_id', $data['id'])->delete();
		if (isset($data['images'])) {
			foreach ($data['images'] as $image) {
				GoodsImage::create([
					'goods_id' => (int) $data['id'],
					'weid' => weid(),
					'image' => $image['url']
				]);
			}
		}
	}

	function getgoodssku()
	{
		$id =  $this->request->post('id', '', 'serach_in');
		$data['attribute'] = GoodsSku::get_goods_sku($id);
		$data['sourceAttribute'] = $data['attribute'];
		return $this->json(['data' => $data]);
	}

	function getInfo()
	{
		$id =  $this->request->post('id', '', 'serach_in');
		//if (!$id) throw new ValidateException('参数错误');
        if(!empty($this->ocid)){
            $model  = new GoodsAudit();
        }else{
            $model  = new Goods();
        }
		if ($id) {
			$data = $model->field('*')->find($id)->toArray();
			if(!empty($this->ocid)){
                $id   = $data['goods_id'];
            }

		} else {
			$data = [
				'is_times' => 0,
				'sort' => 100,
				'status' => 1,
			];
		}

		$GD = GoodsDescription::where(['goods_id' => $id])->find();

		if (!empty($GD)) {
			$data['description'] = $GD->description;
		}

		$goods_image = GoodsImage::where(['goods_id' => $id,'type'=>1])
			->field('image')
			->order('id asc')
			->select()->toArray();

		if (!empty($goods_image)) {
			foreach ($goods_image as $key => $vo) {
				$data['images'][$key]['url'] = toimg($vo['image']);
			}
		}

		$data['attribute'] = GoodsSku::get_goods_sku($id);
		$data['sourceAttribute'] = $data['attribute'];

		$MGDiscountarray = GoodsMemberDiscount::where(['goods_id' => $id])->select()->toArray();

		if (!empty($MGDiscountarray)) {
			$MGDiscount = [];
			foreach ($MGDiscountarray as $vo) {
				$MGDiscount[$vo['mgid']] = $vo['price'];
			}
		}

		$data['MemberGroup'] = MemberAuthGroup::getGroup();
		foreach ($data['MemberGroup'] as &$mvo) {
			if (!empty($MGDiscount[$mvo['id']])) {
				$mvo['price'] = $MGDiscount[$mvo['id']];
			}
		}


		$data['sku'] = GoodsSkuValue::field('sku,image,quantity,price')->where(['goods_id' => $id])
			->order('id asc')
			->select()->toArray();

		$data['sharelevel'] = (int) Config::getconfig('agent')['level'];

		$sharechargesarray = GoodsShareCharges::where(['goods_id' => $id])->select()->toArray();

		if (!empty($sharechargesarray)) {
			foreach ($sharechargesarray as $vo) {
				$sharecharges[$vo['level']]['price'] = $vo['price'];
			}
		}

		for ($i = 1; $i <= $data['sharelevel']; $i++) {
			$data['sharecharges'][$i]['price'] = $sharecharges[$i]['price'];
			$data['sharecharges'][$i]['level'] = $i;
			if ($i == 1) {
				$data['sharecharges'][$i]['title'] = '一层佣金';
				$data['sharecharges'][$i]['help_block'] = '注：一层为顾客的直接上级（如果开启分销内购,分销商自己购买商品，享受一层佣金）';
			}
			if ($i == 2) {
				$data['sharecharges'][$i]['title'] = '二层佣金';
				$data['sharecharges'][$i]['help_block'] = '注：二层为顾客的上上级';
			}
			if ($i == 3) {
				$data['sharecharges'][$i]['title'] = '一层佣金';
				$data['sharecharges'][$i]['help_block'] = '注：三层为顾客的上上上级';
			}
		}

		return $this->json(['data' => $data]);
	}

	function delete()
	{
		$idx =  $this->request->post('id', '', 'serach_in');
		if (!$idx) throw new ValidateException('参数错误');
        if (!empty($this->ocid)) {
            $data  = GoodsAudit::whereIn('id',$idx)->select()->toArray();
            foreach ($data as $k=>$v){
                Goods::destroy(['id' =>$v['goods_id']], true);
            }
            GoodsAudit::destroy(['id' => explode(',', $idx)], true);
        }else{
            Goods::destroy(['id' => explode(',', $idx)], true);
            GoodsAudit::destroy(['goods_id' => explode(',', $idx)], true);
        }
		return $this->json(['msg' => '操作成功']);
	}
	function getField()
	{
		$ptype = input('post.ptype');
//        if(!empty($this->ocid)){
//            $cate_ids = Operatingcity::where(['id'=>$this->ocid])->value('cate_ids');
//            $data = Category::getpcarraytow($ptype,$cate_ids);
//        }elseif(!empty($this->sid)){
//            $cate_ids = Store::where(['id'=>$this->sid])->value('cate_ids');
//            $data = Category::getpcarraytow($ptype,$cate_ids);
//        }else{
//            $data = Category::getpcarray($ptype);
//        }
        $data = Category::getpcarray($ptype);
		$data['cidarray'] = _generateSelectTree($data);
		return $this->json(['data' => $data,'id'=>$this->ocid]);
	}

	public function tongbu(){
        $weid = weid();
        if (empty($this->ocid)) {
            throw new ValidateException('同步失败');
        }
        $ptype      = input('ptype');
        if(!$ptype){
            $ptype = 2;
        }
//        $cate_ids = Operatingcity::where(['id'=>$this->ocid])->value('cate_ids');
        $goods_data = Goods::where(['ptype'=>$ptype,'ocid'=>0])->select();
        $goods_data = $goods_data->toArray();
        if(!$goods_data){
            return $this->json(['msg' => '无数据'.$ptype]);
        }

        foreach ($goods_data as $k=>$v){
            $goods_id = $v['id'];
            unset($v['id']);
            $ocmod           = Operatingcity::find($this->ocid);
            if ($ocmod) {
                $v['province_name'] = $ocmod->province_name;
                $v['city_name']     = $ocmod->city_name;
                $v['district_name'] = $ocmod->district_name;
            }
            $v['ocid']         = $this->ocid;
            $v['audit_status'] = 2;
            $v['ptype']        = $ptype;
            $goods_audit_info = GoodsAudit::where(['name'=>$v['name'],'ocid'=>$this->ocid,'ptype'=>$ptype])->find();
            if($goods_audit_info){
                $v['id'] = $goods_audit_info['id'];
                GoodsAudit::update($v);
                $v['id'] = $goods_audit_info['goods_id'];
                $this->_synupdata($v);
            }else{
                $res = Goods::create($v);
                $v['id'] = $res['id'];
                $this->_synupdata($v);

               $image = GoodsImage::where('goods_id', $goods_id)->select()->toArray();
                if ($image) {
                    foreach ($image as $key=>$val) {
                        GoodsImage::create([
                            'goods_id' => $res['id'],
                            'weid' => weid(),
                            'image' => $val['image']
                        ]);
                    }
                }


                unset($v['id']);
                $v['goods_id']     = $res->id;
                $v['weid']         = $weid;
                $v['create_time']  = time();
                $v['audit_time']   = time();
                $v['update_time']  = time();
                GoodsAudit::create($v);
            }

        }
        return $this->json(['msg' => '同步成功']);
    }
}
